package token

import (
	"encoding/base64"
	"github.com/mitchellh/cli"
	"my-go-cli/utils"
)

// DecodeCommand 结构
type DecodeCommand struct{}

// Help 帮助
func (d *DecodeCommand) Help() string {
	return "对信息进行解密处理"
}

// Run 运行
func (d *DecodeCommand) Run(args []string) int {
	if len(args) != 1 {
		println("请输入待解密的字符串！")
		return 2
	}
	s, err := decrypt(args[0], aesKey)
	if err != nil {
		printErr(err, 3)
		return 2
	}
	println(s)
	return 1
}

// Synopsis 显示概要
func (d *DecodeCommand) Synopsis() string {
	return "对信息进行解密处理"
}

// DecodeCommandFactory 工厂
func DecodeCommandFactory() (cli.Command, error) {
	return new(DecodeCommand), nil
}

func decrypt(rawData string, key []byte) (string, error) {
	data, err := base64.RawURLEncoding.DecodeString(rawData)
	if err != nil {
		return "", err
	}
	dnData, err := utils.AesCBCDecrypt(data, key)
	if err != nil {
		return "", err
	}
	return string(dnData), nil
}
